eval 'exec perl -wS $0 ${1+"$@"}'
 if 0;

use strict;
use warnings;
use POSIX qw(strftime);

use DBI();
use File::Basename;
use File::stat;

# Following variable is used as a general file descriptor for all the 
# output of the current tool (the log file). Actually, this file will
# contain the copy of both the stdout and stderr channel.
my $G_LOG;

my $G_SIMLOCKS_PATH="/data/samba_share/simlocks";

################################################################################
#
################################################################################
sub get_time
  {
    my $separator=shift @_;
    my @timelist = @_;

    my $now_time="";

    if (! defined $separator)
      {
	$separator=":";
      }

    if (scalar @timelist<1)
    {
	@timelist=localtime();
    }

    $now_time = strftime("%H".$separator."%M".$separator."%S",@timelist);

    return $now_time;
  }

################################################################################
#
################################################################################
sub get_date
  {
    my $separator=shift @_;
    my @timelist = @_;

    my $now_date="";

    if (! defined $separator)
      {
	$separator="/";
      }

    if (scalar @timelist<1)
    {
	@timelist=localtime();
    }

    $now_date = POSIX::strftime("%Y".$separator."%m".$separator."%d",@timelist);

    return $now_date;
  }



################################################################################
#
################################################################################
sub mylog
{
    if ($G_LOG)
    {
	print $G_LOG get_date()." ".get_time()." ".join("",@_);
    }
}

################################################################################
#
################################################################################
sub error
  {
    print STDERR get_date()." ".get_time()." [ERROR] ",@_;
    mylog "[ERROR] ", @_;
  }

################################################################################
#
################################################################################
sub warning
  {
    print STDERR get_date()." ".get_time()." [WARNING] ",@_;
    mylog("[WARNING],",@_);
  }

################################################################################
#
################################################################################
sub debug
  {
    my $h_ref_param=shift @_;

    if (exists $h_ref_param->{DEBUG})
      {
	print STDOUT get_date()." ".get_time()." [DEBUG] ",@_;
	mylog("[DEBUG] ",@_);
      }
  }

################################################################################
#
################################################################################
sub info
{
    print STDOUT get_date()." ".get_time()." [INFO] ",@_;
    mylog("[INFO] ",@_);
}


################################################################################
#
################################################################################
sub print_h_content
{
    my $h_ref_param=shift @_;

    debug $h_ref_param, "Printing Global Hash Content:\n";
    debug $h_ref_param, "######################################################\n";
    foreach my $thekey (keys %$h_ref_param)
    {
	debug $h_ref_param, $thekey." => ".$h_ref_param->{$thekey}."\n";
    }
    debug $h_ref_param, "######################################################\n";
}

################################################################################
#
################################################################################
sub db_connect
{
    my $h_ref_param=shift @_;

    my $dbh = DBI->connect("DBI:mysql:database=".$h_ref_param->{DBNAME}.";host=localhost",
                         $h_ref_param->{DBLOGIN}, $h_ref_param->{DBPASSWD},
                         {'RaiseError' => 0});

    $h_ref_param->{DB}=$dbh;

    return (defined $dbh);
}

################################################################################
#
################################################################################
sub db_disconnect
{
    my $h_ref_param=shift @_;
    $h_ref_param->{DB}->disconnect();
}

################################################################################
#
################################################################################
sub db_seed_insert
{
    my $h_ref_param=shift @_;

    my $ref_imei=shift @_;
    my $product = shift @_;
    my $create_date = shift @_;
    my $insert_date = "";
    my $l_ref_keys=shift @_;

    my $opl_id=shift @_;

    my $k1="";
    my $k2="";
    my $k3="";
    my $k4="";
    my $k5="";
    my $k6="";

    my $res=1;

    $k1=@$l_ref_keys[0];
    $k2=@$l_ref_keys[1];
    $k3=@$l_ref_keys[2];
    $k4=@$l_ref_keys[3];
    $k5=@$l_ref_keys[4];
    

    if ($$product eq "seed")
    {
	$k6=@$l_ref_keys[5];
    }
    
    foreach (@$l_ref_keys) {
	debug $h_ref_param, "keys: ".$_ ."\n";
    } 
    
    #debug $h_ref_param, "ref_imei: ".\$$ref_imei." -> ".join(",",$$ref_imei)."\n";
    debug $h_ref_param, "ref_imei: ".\$$ref_imei." -> ".$$ref_imei."\n";
    debug $h_ref_param, "l_ref_keys: ".\@$l_ref_keys." -> ".join(",",@$l_ref_keys)."\n";
    
    $insert_date=get_date("-")." ".get_time(":");
    
    my $sth = $h_ref_param->{DB}->prepare("SELECT COUNT(*) FROM seed WHERE IMEI='$$ref_imei';");
    
    $res=$sth->execute();

    my $result = $sth->fetchrow_hashref();
    $sth->finish();
    
    if ($result->{'COUNT(*)'} == 0)
    {
	$sth = $h_ref_param->{DB}->prepare("INSERT INTO seed (IMEI,CODOPL,PRODUIT,DATREC,DATINT,K1,K3,K5,K7,K9,K11) VALUES ( '$$ref_imei', '$opl_id', '$$product', '$create_date', '$insert_date', '$k1','$k2','$k3','$k4','$k5','$k6');");
	debug $h_ref_param, "INSERTING\n";
    }
    else
    {
	$sth = $h_ref_param->{DB}->prepare("UPDATE seed SET CODOPL='$opl_id',PRODUIT='$$product',DATREC='$create_date',DATINT='$insert_date',K1='$k1',K3='$k2',K5='$k3',K7='$k4',K9='$k5',K11='$k6' WHERE IMEI='$$ref_imei';");
	debug $h_ref_param, "UPDATING\n";

    }
    
    $res=$sth->execute();
    $sth->finish();
    
    return $res;
}


################################################################################
#
################################################################################
sub process
{
    my $h_ref_param=shift @_;
    my $err=0;
    my $imei=$h_ref_param->{IMEI};
    my $report="";
    my $res=0;

    if (! db_connect($h_ref_param))
    {
	error("Failed to connect to database.\n");
	$res=1;
	goto end_of_process;
    }

    # First checking that given IMEI really exists.
    my $sth = $h_ref_param->{DB}->prepare("SELECT COUNT(*) FROM imei WHERE IMEI=$imei;");
    
    $res=$sth->execute();

    my $result = $sth->fetchrow_hashref();
    $sth->finish();
    
    $report="$imei";

    if ($result->{'COUNT(*)'} == 0)
    {
	$report.="\t<Record not found>\n";
	print $report;
	$res=2;
	goto end_of_process;
    }

    $report.="\t".$result->{'COUNT(*)'};

    # Here we are sure at least one record exists.

    my $query="SELECT 
                      imei,
                      ref_com,
                      opl.num_opl,
                      insert_date,
                      nb_imei_opl,
                      company.name,
                      code_client 
                FROM 
                      imei,
                      opl,
                      event,
                      company,
                      client 
                WHERE 
                      imei=11467005324809 
                  AND imei.event_id=event.id 
                  AND opl.id=event.data 
                  AND opl.client_id=client.id 
                  AND client.company_id=company.id;";

    $sth = $h_ref_param->{DB}->prepare($query);
    $res=$sth->execute();

    $report.="\t";

    while($result = $sth->fetchrow_hashref())
    {
	$report.="(".$result->{'num_opl'}.",".$result->{'insert_date'}.",".$result->{'ref_com'}.",".$result->{'nb_imei_opl'}.",".$result->{'code_client'}.")";
    }

    $report.="\n";

    $sth->finish();

    print $report;

    $res=0;
    
end_of_process:    
    if (! db_disconnect($h_ref_param))
    {
	error("Failed to disconnect from database.\n");
	$err=4;
    }

    debug $h_ref_param, "Processing finished with status=$err \n";
    
    return $err;
}

################################################################################
#
################################################################################
sub print_version
{
  my $h_ref_param=shift @_;
  print $h_ref_param->{EXECUTABLE_NAME}." ".$h_ref_param->{VERSION}." ".$h_ref_param->{RELEASE_DATE}."\n";
}

################################################################################
#
################################################################################
sub parse_args
{
    my $h_ref_param=shift @_;
    
    my $arg="";
    my $err=0;
    
    while ($arg=shift @ARGV)
    {
	chomp($arg);
	if ( $arg =~ /^-/ )
	{
	    if ( ($arg =~ /^-h/) || ($arg =~ /^--help/))
	    {
		print_usage($h_ref_param);
		exit(0);
	    }
	    elsif ( ($arg =~ /^-d/) || ($arg =~ /^--debug/))
	    {
		$h_ref_param->{DEBUG}=1;
	    }
	    elsif ( ($arg =~ /^-v/) || ($arg =~ /^--version/))
	    {
		print_version();
		exit(0);
	    }
	    
	    elsif ( ($arg =~ /^-l/) || ($arg =~ /^--log/))
	    {
		$arg=shift @ARGV;
		$h_ref_param->{LOG}=$arg;
	    }

	    else
	    {
		error "Unexpected option >$arg<.\n";
		$err++;
		next;
	    } 
	}
	else
	{
	    #<dbname>: Mandatory. Local database name to use to check for already downloaded archives.\n";
	    if (! exists $h_ref_param->{DBNAME})
	    {
		$h_ref_param->{DBNAME}=$arg;
	    }
	    #<dblogin>: Mandatory. Local database login to use <dbname> database.\n";
	    elsif (! exists $h_ref_param->{DBLOGIN})
	    {
		$h_ref_param->{DBLOGIN}=$arg;
	    }
	    #<dbpasswd>: Mandatory. Local database password to use <dbname> database.\n";
	    elsif (! exists $h_ref_param->{DBPASSWD})
	    {
		$h_ref_param->{DBPASSWD}=$arg;
	    }
	    #<imei>: Mandatory. 
	    elsif (! exists $h_ref_param->{IMEI})
	    {
		$h_ref_param->{IMEI}=$arg;
	    }
	    else
	    {
		error("Unexpected argument '$arg'.\n");
		$err++;
	    }
	}
    }
    
    if (! exists $h_ref_param->{IMEI})
    {
	error("Missing arguments.\n");
	$err++;
    }
    
    if ($err>0)
    {
	error "Aborting due to previous error(s). Use -h or --help for usage.\n";
	return 1;
    }
    
    return 0;
}
    
################################################################################
#
################################################################################
sub print_usage
  {
    my $h_ref_param=shift @_;

    print "USAGE: ".$h_ref_param->{EXECUTABLE_NAME}." [-h|--help] [-d|--debug] [-v|--version] [-l|--log <log file>] ...] <dbname> <dblogin> <dbpasswd> <imei>\n";
    print "\n";
    print "PURPOSE:\n";
    print "  Print summary of history for the given IMEI.\n";
    print "\n";
    print "PARAMETERS DESCRIPTION:\n";
    print "\n";
    print "   <dbname>: Mandatory. Local database name to use to check for already downloaded archives.\n";
    print "\n";
    print "   <dblogin>: Mandatory. Local database login to use <dbname> database.\n";
    print "\n";
    print "   <dbpasswd>: Mandatory. Local database password to use <dbname> database.\n";
    print "\n";
    print "   <imei>: Mandatory. IMEI to look history for.\n";
    print "\n";
    print "OPTIONS DESCRIPTION:\n";
    print "   [-h|--help]:\n";
    print "      Print this usage message and exit.\n";
    print "\n";
    print "   [-v|--version]:\n";
    print "      Print the version number and exit.\n";
    print "\n";
    print "   [-d|--debug]:\n";
    print "      Print excessive output to understand the processing.\n";
    print "\n";
    print "\n";
  }

################################################################################
#
################################################################################
sub open_log
{
    my $h_ref_param=shift @_;

    if (! open($G_LOG,">>".$h_ref_param->{LOG}))
    {
	warning "Cannot create log file ".$h_ref_param->{LOG}." in current directory.\n";

	$h_ref_param->{LOG}="/tmp/".$h_ref_param->{EXECUTABLE_NAME}.".log";

	if (! open($G_LOG,">".$h_ref_param->{LOG}))
	{
	    warning "Still cannot create alternative log file ".$h_ref_param->{LOG}.". No log will be performed.\n";
	    $G_LOG=0;
	}
    }
}


################################################################################
#
################################################################################
sub intro
  {
    my $h_ref_param=shift @_;
    my $err=0;
    my $date_for_file="";

    # Updating some global variables.

    $h_ref_param->{START_TIME}=get_date("-")." ".get_time(":");

    $date_for_file=get_date("-")."_".get_time("-");
    
    $h_ref_param->{VERSION}="0.3.2";
    $h_ref_param->{EXECUTABLE_NAME}="import_seed.pl";

    $h_ref_param->{LOG}=$h_ref_param->{EXECUTABLE_NAME}.".$date_for_file.log";

    $h_ref_param->{LOCK_FILE}="/tmp/".$h_ref_param->{EXECUTABLE_NAME}.".lock";
    
    $h_ref_param->{RELEASE_DATE}="2007/10/12";

    # Following instruction forces flushing for each output to STDOUT or STDERR.
    $|=1;

    return 0;
  }

################################################################################
#
################################################################################
sub outtro
{
    my $h_ref_param=shift @_;
    if ($G_LOG)
    {
	close($G_LOG);
    }

    return 0;
}

################################################################################
#
################################################################################
sub main
{
  # This hash list will be used to store input parameters and some other
  # usefull information.
  # The actual valable keys are:
  #   VERSION:           string: current version of the tool.
  #   START_TIME:        string: start time of the script in the form YY_MM_DD.HH.MM.SS
  #   EXECUTABLE_NAME:   string: name of the current script.
  #   LOG:               string: name of the log file.
  #   RELEASE_DATE:      string: date of current tool release in form: YYYY/MM/DD
  #   DEBUG:             boolean: if this key exists, then the current script is run in
  #                               debug mode.
  #
  my %params=();
  
  if (intro(\%params)!=0)
  {
      error "Error while executing intro ... Aborting.\n";
      exit(1);
  }

  if (parse_args(\%params)!=0)
  {
      error "Error while parsing arguments ... Aborting.\n";
      exit(1);
  }
  
  open_log(\%params);

  if (process(\%params)!=0)
  {
      error "Error while processing ... Aborting.\n";
      exit(1);
  }

  if (outtro(\%params)!=0)
  {
      error "Error while executing outtro ... Aborting.\n";
      exit(1);
  }


}


################################################################################
#
################################################################################

main();
exit(0);

